package com.nulldev.util.networking.async2.tcp.client.connectors;

import com.nulldev.util.networking.async2.ByteArrayBuilder;
import com.nulldev.util.networking.async2.DataFrame;

public class TCPClientMessageCollector {
	private TCPConnector fMyConnector;
	private final byte[] fETXStr;
	private final ByteArrayBuilder fIncomingDataBuffer = new ByteArrayBuilder();
	private final int fETXLength;
	private int fIndexOfETX;

	public TCPClientMessageCollector(TCPConnector connector, char ETX) {
		fMyConnector = connector;
		fETXStr = String.valueOf(ETX).getBytes();
		fETXLength = fETXStr.length;
	}

	public TCPClientMessageCollector(TCPConnector connector, String splitter) {
		fMyConnector = connector;
		fETXStr = splitter.getBytes();
		fETXLength = fETXStr.length;
	}

	public void appendData(byte[] bytes) {
		try {
			fIncomingDataBuffer.append(bytes);
			fIndexOfETX = fIncomingDataBuffer.indexOf(fETXStr);
			while (fIndexOfETX > -1) {
				fMyConnector.getTCPClient().onDataReceive(fMyConnector, new DataFrame(fIncomingDataBuffer.subList(0, fIndexOfETX)));
				fIncomingDataBuffer.delete(0, fIndexOfETX + fETXLength);
				fIndexOfETX = fIncomingDataBuffer.indexOf(fETXStr);
			}
		} catch (Exception ex) {
		}
	}

	public void dispose() {
		try {
			fMyConnector = null;
		} catch (Exception ex) {
		}
	}
}
